<?php
class ranking_model extends CI_Model{
	
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	
	
	
	/**
	 * Obtener lista de banners
	 */
	public function rating($params){
		if($params['type'] == 'film'){
			$exist = $this->exist('peliculas', 'id_pelicula = '.$params['id']);
			$tbl_conf = array('peliculas_ranking', 'id_pelicula');
		}else{
			$exist = $this->exist('series_capitulos', 'id_capitulo = '.$params['id']);
			$tbl_conf = array('series_capitulos_ranking', 'id_capitulo');
		}
		
		if($exist){
			$this->load->model('user_model');
			$res = $this->user_model->getIdUserToken($params);
			//informacion del usuario
			$data_usr = $res->row_array();
			
			$rank = $this->exist($tbl_conf[0], 'id_usuarios = '.$data_usr['id_usuario'].' AND '.$tbl_conf[1].' = '.$params['id']);
			if($rank){
				$this->db->update($tbl_conf[0], array('calificacion' => $params['rating']), 
					'id_usuarios = '.$data_usr['id_usuario'].' AND '.$tbl_conf[1].' = '.$params['id']);
			}else{
				$this->db->insert($tbl_conf[0], 
					array(
						'calificacion' => $params['rating'],
						'id_usuarios' => $data_usr['id_usuario'],
						$tbl_conf[1] => $params['id']
					)
				);
			}
			return TRUE;
		}
		return FALSE;
	}


	
	private function exist($table, $sql, $return_res=false){
		$res = $this->db->get_where($table, $sql);
		if($res->num_rows() > 0){
			if($return_res)
				return $res->row();
			return TRUE;
		}
		return FALSE;
	}
}